package com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.StudentList.Adapter;

import static com.example.tnot.login.fragmentui.LoginFragment.BASE_URL;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.tnot.R;
import com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.StudentList.ItemBean.rv_StudntListItem;

import java.util.List;

public class rv_StudentListAdapter extends RecyclerView.Adapter<rv_StudentListAdapter.ViewHolder>{
    private List<rv_StudntListItem> mData;
    private int CurrentPosition;
    public static String BASE_AVATAR_URL=BASE_URL+"/api/get_user_avatar/";
    public rv_StudentListAdapter(List<rv_StudntListItem> mData) {
        this.mData = mData;
    }

    private OnDeleteClickListener onDeleteClickListener;

    // 添加删除回调接口
    public interface OnDeleteClickListener {
        void onDeleteClick(int position);
    }

    // 设置删除监听器的方法
    public void setOnDeleteClickListener(OnDeleteClickListener listener) {
        this.onDeleteClickListener = listener;
    }

    @NonNull
    @Override
    public rv_StudentListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_course_detail_student_list,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull rv_StudentListAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        CurrentPosition = holder.getBindingAdapterPosition();
        rv_StudntListItem item = mData.get(position);

        holder.tv_ID.setText(item.getID());
        holder.tv_name.setText(item.getName());
        holder.tv_gender.setText(item.getSex());
        holder.tv_class.setText(item.getClassname());

        // 设置成绩和状态
        holder.tv_score.setText(item.getScore());
        holder.tv_status.setText(item.getStatus());

        // 根据状态设置背景色
        if(item.getStatus().equals("未通过")){
            holder.tv_status.setBackgroundColor(0xFFFEE2E2);
        } else if(item.getStatus().equals("通过")) {
            holder.tv_status.setBackgroundColor(0xFFA5D6A7);
        }

        String imageUrl = BASE_AVATAR_URL + mData.get(position).getID();

        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.example_face)
                .error(R.drawable.example_face)
                .transform(new CenterCrop(), new RoundedCorners(8));

        Glide.get(holder.itemView.getContext()).clearMemory();  // 清除内存缓存（需在主线程）
        new Thread(() -> {
            // 清除磁盘缓存（需在子线程）
            Glide.get(holder.itemView.getContext()).clearDiskCache();
        }).start();

        Glide.with(holder.itemView.getContext())
                .load(imageUrl)
                .apply(options)
                .into(holder.iv_icon);

       // holder.iv_icon.setImageResource(mData.get(position).getIcon());

        holder.tv_look.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                Bundle bundle = new Bundle();
                //将数据传给学生详细信息页面
                bundle.putString("ID",mData.get(position).getID());
                bundle.putString("name",mData.get(position).getName());
                bundle.putString("class",mData.get(position).getClassname());
                bundle.putString("score",mData.get(position).getScore());
                bundle.putString("icon",imageUrl);
                bundle.putString("telephone",mData.get(position).getTelephone());
                bundle.putString("CourseTeacher",mData.get(position).getTeacher());
                navController.navigate(R.id.action_studentListFragment_to_studentDetailFragment,bundle);
            }
        });
        holder.tv_score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.tv_score.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        String scoreText = s.toString().trim();
                        if (!scoreText.isEmpty()) {
                            try {
                                int score = Integer.parseInt(scoreText);

                                // 根据分数设置状态
                                if (score < 60) {
                                    holder.tv_status.setText("未通过");
                                    holder.tv_status.setBackgroundColor(0xFFFEE2E2); // 浅红色
                                } else {
                                    holder.tv_status.setText("通过");
                                    holder.tv_status.setBackgroundColor(0xFFA5D6A7); // 浅绿色
                                }

                                // 确保更新数据源中的数据
                                rv_StudntListItem item = mData.get(position);
                                item.setScore(scoreText);
                                item.setStatus(holder.tv_status.getText().toString());

                            } catch (NumberFormatException e) {
                                // 处理无效输入
                                holder.tv_status.setText("无效分数");
                                holder.tv_status.setBackgroundColor(0xFFEEEEEE); // 灰色
                            }
                        } else {
                            // 输入为空时的处理
                            holder.tv_status.setText("未评分");
                            holder.tv_status.setBackgroundColor(0xFFEEEEEE);
                        }
                    }
                });
            }
        });



        holder.tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getBindingAdapterPosition();
                if (position != RecyclerView.NO_POSITION && onDeleteClickListener != null) {
                    onDeleteClickListener.onDeleteClick(position);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return mData == null? 0: mData.size();
    }
    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView tv_ID,tv_name,tv_gender,tv_class,tv_score,tv_status,tv_look,tv_delete;
        ImageView iv_icon;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_ID = itemView.findViewById(R.id.tv_ID);
            tv_name = itemView.findViewById(R.id.tv_name);
            tv_gender = itemView.findViewById(R.id.tv_gender);
            tv_class = itemView.findViewById(R.id.tv_class);
            tv_score = itemView.findViewById(R.id.tv_score);
            tv_status = itemView.findViewById(R.id.tv_status);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_look = itemView.findViewById(R.id.tv_look);
            tv_delete = itemView.findViewById(R.id.tv_delete);
        }
    }
    public void updateList(List<rv_StudntListItem> newList) {
        this.mData = newList;
        notifyDataSetChanged();
    }
}
